package pkg

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"net/http"
	"time"
)

type MyCustomClaims struct {
	UserId uint `json:"userId"`
	jwt.RegisteredClaims
}

func Token(UserId uint, duration time.Duration, JWT_KEY string) string {
	claims := MyCustomClaims{
		UserId,
		jwt.RegisteredClaims{
			// Also fixed dates can be used for the NumericDate
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 10)),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString([]byte(JWT_KEY))
	fmt.Println(ss, err)
	return ss
}
func GetToken(JWT_KEY string) gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("token")
		if tokenString == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": 400,
				"mes":  "未登录",
				"data": false,
			})
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{})
			return
		}
		token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {
			return []byte(JWT_KEY), nil
		})
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": 400,
				"mes":  "未登录",
				"data": false,
			})
			c.Abort()
			return
		}
		claims, _ := token.Claims.(*MyCustomClaims)
		if claims.UserId == 0 {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": 400,
				"mes":  "未登录",
				"data": false,
			})
			c.Abort()
			return
		}
		c.Set("userId", claims.UserId)
		c.Next()
	}

}
